package com.example.demo.domain.interceptor;

import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTUtil;
import com.example.demo.common.ThreadLocalUtil;
import com.example.demo.controller.UserController;
import com.example.demo.exception.MyException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

//实现HandlerInterceptor接口
//@Component进入Spring管理
@Component
public class    MyInterceptor implements HandlerInterceptor{
    @Autowired
    StringRedisTemplate stringRedisTemplate;


    @Override//处理请求之前的事情
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("正在拦截："+request.getRequestURI());
        //预先设置错误代码
        response.setStatus(444);

        //获取token并立即进行判定
        String token = request.getHeader("token");
        if(token == null || token.isEmpty()){
            throw new MyException("没有检测到令牌！");
        }
//        System.out.println("getRemoteUser=>"+request.getRemoteUser());

        //检查令牌时效性,需要Redis辅助
        ValueOperations<String, String> valueOperations = stringRedisTemplate.opsForValue();
        String redisToken = valueOperations.get(UserController.user);
        if(redisToken == null || redisToken.isEmpty()){
            throw new MyException("请先登录！");
        }

        //继续验证token
        try {//捕获多种未知异常
            if((!JWTUtil.verify(redisToken,"123456".getBytes())) || (!JWTUtil.verify(token,"123456".getBytes()))){
                throw new MyException("Redis中token非法，请重新登录后再试！");
            }
        }catch (Throwable e){
            throw new MyException("token非法，请重新登录后再试！");
        }
        //最后验证
        if(!token.equals(redisToken)){
            throw new MyException("您的token已失效，请重新登录后再试！");
        }
        response.setStatus(200);
        //获取用户信息
        JWT jwt = JWTUtil.parseToken(token);
        String username = (String) jwt.getPayload("username");
//        System.out.println("username:"+username);
        //name需要共享，由线程保管且私有
        ThreadLocalUtil.set(username);
        System.out.println("结束拦截："+request.getRequestURI());
        return true;
    }

    @Override//处理响应之前还没有渲染到前端的事情
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
//        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override//处理渲染到前端之后处理的事情
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
//        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
        //清理ThreadLocal
        ThreadLocalUtil.remove();
    }


}
